<?php
// +----------------------------------------------------------------------
// | ZGUAN [ 致力于帮助更多的中小账单物联网转型 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.zguan.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ZGUAN 并不是自由软件，未经许可不能去掉ZGUAN 相关版权
// +----------------------------------------------------------------------
// | Author: ZGUAN Team <admin@zguan.cn>  0769-82282996  15899929162
// +----------------------------------------------------------------------
namespace app\controller\property\bill;

use think\App;
use app\controller\property\Base;
use app\validate\bill\BillBasicValidate;
use app\common\repositories\bill\BillCateRepository;
use app\common\repositories\bill\BillBasicRepository;
use app\common\repositories\property\basic\PropertyBasicRepository;

class BillExpend extends Base
{

    protected $repository;

    public function __construct(App $app, BillBasicRepository $repository)
    {
        parent::__construct($app);

        $this->repository = $repository;
        $this->assign([
            'addAuth' => property_auth('propertyBillExpendAdd'),
            'editAuth' => property_auth('propertyBillExpendEdit'),
            'delAuth' => property_auth('propertyBillExpendDel'),
            'detailAuth' => property_auth('propertyBillExpendDetail'),
            'paymentAuth' => property_auth('propertyBillPaymentSubmit'),
            'postponeAuth' => property_auth('propertyBillPostponeSubmit'),
        ]);
    }

    protected function commonParams()
    {
        /** @var BillCateRepository $cateRepository */
        $cateRepository = app()->make(BillCateRepository::class);
        $cateNameData = $cateRepository->getCascaderData(['is_show' => 1]);
        $this->assign([
            'cateNameData' => $cateNameData,
        ]);
    }


    /**
     *  账单列表
     * @return string|\think\response\Json
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-30 10:48
     */
    public function list()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'contract_id' => '',
                'keywords' => ''
            ]);
            $where['is_type'] = 2;
            [$page, $limit] = $this->getPage();
            $data = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $data['list'], 'count' => $data['count']]);
        }
        return $this->fetch('bill/expend/list');
    }

    /**
     * 待支付账单
     * @return string|\think\response\Json
     * @throws \Exception
     *
     * @author Amos
     * 2024-03-15 16:33
     */
    public function stayPaymentList()
    {
        if ($this->request->isAjax()) {
            $where = $this->request->param([
                'contract_id' => '',
                'month_time' => '',
                'keywords' => '',
            ]);
            $where['is_type'] = 2;
            $where['status'] = [2, 8];
            [$page, $limit] = $this->getPage();
            $res = $this->repository->getpropertyList($where, $page, $limit, $this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $res['list'], 'count' => $res['count']]);
        }
        $this->commonParams();
        return $this->fetch('bill/expend/stay_pay_bill_list', [
            'invalidAuth' => property_auth('propertyBillInvalidSubmit'),
            'paymentAuth' => property_auth('propertyBillPaymentSubmit'),
        ]);
    }


    /**
     * 添加账单
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-30 10:48
     */
    public function add()
    {
        if ($this->request->isAjax() && $this->request->isGet() && $this->request->param('get_type') == 'roomData') {
            $roomData['number'] = $this->repository->generateBillNumber($this->request->propertyId);
            return json()->data(['code' => 0, 'data' => $roomData]);
        } else if ($this->request->isPost()) {
            $param = $this->request->param([
                'number' => '',
                'room_id' => '',
                'other_fee' => [],
                'remark' => '',
            ]);
            $param['is_type'] = 2;
            $param['bill_type'] = 4;
            $param['month_time'] = date('Y-m');
            validate(BillBasicValidate::class)->scene('expendAdd')->check($param);
            try {
                $res = $this->repository->addInfo($param, $this->request->propertyId, $this->request->userId);
                if ($res) {
                    return $this->success('添加成功');
                } else {
                    return $this->error('添加失败');
                }
            } catch (\Exception $e) {
                exception_log('添加支出账单失败', $e);
                return $this->error('网络失败');
            }
        } else {
            $this->commonParams();
            return $this->fetch('bill/expend/add');
        }
    }

    /**
     * 编辑账单
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-30 10:48
     */
    public function edit()
    {
        $id = (int)$this->request->param('id');
        if (!$id) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($id);
        if (!$info) {
            return $this->error('信息错误');
        }
        if ($this->request->isPost()) {
            $param = $this->request->param([
                'remark' => '',
            ]);
            validate(BillBasicValidate::class)->scene('edit')->check($param);
            try {
                $res = $this->repository->editInfo($info, $param, $this->request->userId);
                if ($res) {
                    return $this->success('修改成功');
                } else {
                    return $this->error('修改失败');
                }
            } catch (\Exception $e) {
                exception_log('编辑支出账单失败', $e);
                return $this->error('网络错误');
            }
        } else {
            return $this->fetch('bill/expend/edit', [
                'info' => $info,
            ]);
        }
    }

    /**
     * 账单详情
     * @return string|\think\response\Json|\think\response\View
     * @throws \Exception
     *
     * @author Amos
     * 2024-01-30 19:09
     */
    public function detail()
    {
        $billId = (int)$this->request->param('bill_id');
        if ($billId <= 0) {
            return $this->error('参数错误');
        }
        $info = $this->repository->getDetail($billId);
        if ($info['id'] <= 0) {
            return $this->error('信息不存在');
        }
        return $this->fetch('bill/expend/detail', [
            'info' => $info,
            'addBasicAuth' => property_auth('propertyBillCatalogAddBasic'),
            'addEnergyAuth' => property_auth('propertyBillCatalogAddEnergy'),
            'addOtherAuth' => property_auth('propertyBillCatalogAddOther'),
            'editCatalogAuth' => property_auth('propertyBillCatalogEdit'),
            'delCatalogAuth' => property_auth('propertyBillCatalogDel'),
            'detailCatalogAuth' => property_auth('propertyBillCatalogDetail'),
            'paymentAuth' => property_auth('propertyBillCatalogPaymentSubmit'),
            'invalidAuth' => property_auth('propertyBillCatalogInvalidSubmit'),
        ]);
    }


    /**
     * 删除账单
     * @return string|\think\response\Json|\think\response\View
     *
     * @author Amos
     * 2024-01-30 10:47
     */
    public function del()
    {
        $ids = (array)$this->request->param('ids');
        $remark = $this->request->param('remark', '');
        try {
            $data = $this->repository->batchDelete($ids, $this->request->userId, $remark);
            if ($data) {
                return $this->success('删除成功');
            } else {
                return $this->error('删除失败');
            }
        } catch (\Exception $e) {
            exception_log('删除支出账单失败', $e);
            return $this->error('网络失败');
        }
    }
}